package org.goldenport.g3.adapters

import scala.xml.{XML, Elem}
import java.io._
import java.net.URL
import org.goldenport.g3._
import org.goldenport.g3.messages._
import org.goldenport.g3.events.file._
import com.asamioffice.goldenport.io.{UFile, UURL, UIO}
import com.asamioffice.goldenport.text.UPathString.concatPathname

/**
 * @since   Sep. 15, 2010
 * @version Sep. 19, 2010
 * @author  ASAMI, Tomoharu
 */
class ResourceAdapter(val uri: String) extends G3Adapter {
  val driver = new ResourceDriver(uri)

  override protected def do_Action(content: AnyRef, parcel: G3Parcel, ctx: G3AgentContext): AnyRef = {
    content match {
      case cmd: G3Command => driver.execute(cmd, ctx)
    }
  }
}

class ResourceDriver(val uri: String, val encoding: String = "utf-8", val mime: Option[String] = None) extends G3Driver {
  protected def new_Agent(cmd: G3Command, ctx: G3AgentContext): ResourceDriverAgent = {
    new ResourceDriverAgent(uri, encoding, mime, ctx)
  }
}

class ResourceDriverAgent(uri: String, val encoding: String, val mime: Option[String], context: G3AgentContext) extends G3DriverAgent(uri, context) {
  def get(get: Get): G3Event = read_file(get.uris)

  def post(post: Post): G3Event = {
    throw new UnsupportedOperationException("post")
  }

  def put(put: Put): G3Event = {
    throw new UnsupportedOperationException("put")
  }

  def delete(delete: Delete): G3Event = {
    throw new UnsupportedOperationException("delete")
  }

  def mkcol(mkcol: Mkcol): G3Event = {
    throw new UnsupportedOperationException("mkcol")
  }

  //
  private def read_file(uris: List[String]): G3Event = {
    if (uris == Nil) {
      val resource = context.getResource(uri)
      val result = context.reconstitute(resource)
      new FileReaded(uri, result)
    } else {
      new FileSetReaded(uris, uris.map(u => {
        val resource = context.getResource(concatPathname(uri, u))
        context.reconstitute(resource)
      }))
    }
  }
}
